package com.atguigu.daijia.driver.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import com.atguigu.daijia.common.constant.SystemConstant;
import com.atguigu.daijia.common.execption.GuiguException;
import com.atguigu.daijia.common.result.ResultCodeEnum;
import com.atguigu.daijia.driver.mapper.DriverAccountMapper;
import com.atguigu.daijia.driver.mapper.DriverInfoMapper;
import com.atguigu.daijia.driver.mapper.DriverLoginLogMapper;
import com.atguigu.daijia.driver.mapper.DriverSetMapper;
import com.atguigu.daijia.driver.service.CosService;
import com.atguigu.daijia.driver.service.DriverInfoService;
import com.atguigu.daijia.driver.util.CloudApiOperator;
import com.atguigu.daijia.model.entity.driver.DriverAccount;
import com.atguigu.daijia.model.entity.driver.DriverInfo;
import com.atguigu.daijia.model.entity.driver.DriverLoginLog;
import com.atguigu.daijia.model.entity.driver.DriverSet;
import com.atguigu.daijia.model.form.driver.DriverFaceModelForm;
import com.atguigu.daijia.model.form.driver.UpdateDriverAuthInfoForm;
import com.atguigu.daijia.model.vo.driver.DriverAuthInfoVo;
import com.atguigu.daijia.model.vo.driver.DriverLoginVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class DriverInfoServiceImpl extends ServiceImpl<DriverInfoMapper, DriverInfo> implements DriverInfoService {
    @Resource
    private WxMaService wxMaService;
    @Resource
    private DriverInfoMapper driverInfoMapper;
    @Resource
    private DriverSetMapper driverSetMapper;
    @Resource
    private DriverLoginLogMapper driverLoginLogMapper;
    @Resource
    private DriverAccountMapper driverAccountMapper;
    @Resource
    private CosService cosService;
    @Resource
    private CloudApiOperator cloudApiOperator;

    /**
     * 司机端登录
     */
    @Override
    public Long login(String code) {
        String openid;
        try {
            openid = wxMaService.getUserService().getSessionInfo(code).getOpenid();
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }
        DriverInfo driverInfo = driverInfoMapper.selectOne(new LambdaQueryWrapper<DriverInfo>().eq(DriverInfo::getWxOpenId, openid));
        if (driverInfo == null) {
            // 注册用户
            driverInfo = new DriverInfo();
            driverInfo.setAvatarUrl("https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
            driverInfo.setNickname("微信用户");
            driverInfo.setWxOpenId(openid);
            driverInfoMapper.insert(driverInfo);

            // 初始化配置
            DriverSet driverSet = new DriverSet();
            driverSet.setDriverId(driverInfo.getId());
            driverSet.setOrderDistance(BigDecimal.ZERO); // 0 无限制
            driverSet.setAcceptDistance(new BigDecimal(SystemConstant.ACCEPT_DISTANCE)); // 默认接单范围 5公里
            driverSet.setIsAutoAccept(0); // 0：否 1：是
            driverSetMapper.insert(driverSet);

            // 初始化账号信息
            DriverAccount driverAccount = new DriverAccount();
            driverAccount.setDriverId(driverInfo.getId());
            driverAccountMapper.insert(driverAccount);
        }

        // 保存登录日志
        DriverLoginLog loginLog = new DriverLoginLog();
        loginLog.setDriverId(driverInfo.getId());
        loginLog.setMsg("小程序登录");
        driverLoginLogMapper.insert(loginLog);
        return driverInfo.getId();
    }

    /**
     * 获取司机登录信息
     */
    @Override
    public DriverLoginVo getDriverInfo(Long driverId) {
        DriverInfo driverInfo = driverInfoMapper.selectById(driverId);
        if (driverInfo == null) {
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }
        DriverLoginVo vo = new DriverLoginVo();
        BeanUtils.copyProperties(driverInfo, vo);
        vo.setIsArchiveFace(StringUtils.hasText(driverInfo.getFaceModelId()));
        return vo;
    }

    /**
     * 获取司机登录认证信息
     */
    @Override
    public DriverAuthInfoVo getDriverAuthInfo(Long driverId) {
        DriverInfo driverInfo = driverInfoMapper.selectById(driverId);
        DriverAuthInfoVo vo = new DriverAuthInfoVo();
        BeanUtils.copyProperties(driverInfo, vo);

        vo.setIdcardBackShowUrl(cosService.getImageUrl(vo.getIdcardBackUrl()));
        vo.setIdcardFrontShowUrl(cosService.getImageUrl(vo.getIdcardFrontUrl()));
        vo.setIdcardHandShowUrl(cosService.getImageUrl(vo.getIdcardHandUrl()));
        vo.setDriverLicenseFrontShowUrl(cosService.getImageUrl(vo.getDriverLicenseFrontUrl()));
        vo.setDriverLicenseBackShowUrl(cosService.getImageUrl(vo.getDriverLicenseBackUrl()));
        vo.setDriverLicenseHandShowUrl(cosService.getImageUrl(vo.getDriverLicenseHandUrl()));
        return vo;
    }

    /**
     * 更新司机认证信息
     */
    @Override
    public Boolean updateDriverAuthInfo(UpdateDriverAuthInfoForm updateDriverAuthInfoForm) {
        DriverInfo driverInfo = new DriverInfo();
        BeanUtils.copyProperties(updateDriverAuthInfoForm, driverInfo);
        driverInfo.setId(updateDriverAuthInfoForm.getDriverId());
        return this.updateById(driverInfo);
    }

    /**
     * 创建司机人脸模型
     */
    @Override
    public Boolean creatDriverFaceModel(DriverFaceModelForm driverFaceModelForm) {
        DriverInfo driverInfo = driverInfoMapper.selectById(driverFaceModelForm.getDriverId());
        if (driverInfo == null) {
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }
        String faceId = cloudApiOperator.creatDriverFaceModel(driverInfo, driverFaceModelForm.getImageBase64());
        if (StringUtils.hasText(faceId)) {
            driverInfo.setFaceModelId(faceId);
            return this.updateById(driverInfo);
        }
        return false;
    }

    /**
     * 获取司机设置信息
     */
    @Override
    public DriverSet getDriverSet(Long driverId) {
        DriverSet driverSet = driverSetMapper.selectOne(new LambdaQueryWrapper<DriverSet>()
                .eq(DriverSet::getDriverId, driverId));
        return driverSet;
    }
}